import React, { useState, useCallback } from "react";
import { bem, isEmpty } from "@/utils";
import "./stepper.scss";
import getMiniDecimal, {
    toFixed, type DecimalClass,
} from '@rc-component/mini-decimal'

export interface StepperProps {
    defaultValue?: number;
    value?: number | null;
    digits?: number;
    disabled?: boolean;
    max?: number;
    min?: number;
    step?: number;
    onInputChange?: (value: number) => void;
}

const defaultProps = {
    defaultValue: 1,
    max: 999,
    min: 1,
    step: 1
}


const Stepper: React.FC<StepperProps> = (props) => {
    const {
        defaultValue,
        value,
        disabled,
        digits,
        max,
        min,
        step,
        onInputChange,
    } = {
        ...defaultProps,
        ...props
    };

    const b = bem('stepper');

    const [inputValue, setInputValue] = useState(value || defaultValue);

    const [focused, setFocused] = useState(false);

    const formatValue = (value: string | number): number => {
        if (isEmpty(value)) return 0;
        const fixedValue = digits !== undefined ? toFixed(value.toString(), '.', digits) : value;
        const decimal = getMiniDecimal(fixedValue)
        return decimal.isInvalidate() ? 0 : Number(decimal.toString());
    }

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        updateInputValue(value);
    }

    const handleAdd = () => {
        const newValue = inputValue + step;
        updateInputValue(newValue);
    }

    const handleReduce = () => {
        const newValue = inputValue - step;
        updateInputValue(newValue);
    }

    const updateInputValue = (value: number | string) => {
        let newValue = formatValue(value);
        if (inputValue === newValue) {
            return;
        }
        if (newValue > max) {
            newValue = max;
        }
        if (newValue < min) {
            newValue = min;
        };
        setInputValue(newValue);
        onInputChange?.(newValue);
    }

    return (
        <div className={b()}>
            <button className={b('btn')} onClick={handleReduce}>-</button>
            <div className="seal-stepper__middle">
                <div className="seal-stepper__input-wrap">
                    <input
                        type="tel"
                        className="seal-stepper__input"
                        value={inputValue}
                        onChange={handleInputChange} />
                </div>
            </div>
            <button className={b('btn')} onClick={handleAdd}>+</button>
        </div>
    );
};

export default Stepper;